<template>
  <div class="profile">
    <div class="profile-header">
      <h2>个人资料</h2>
    </div>

    <el-row :gutter="20">
      <!-- 左侧基本信息 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="avatar-section">
            <div class="avatar-wrapper">
              <el-avatar :size="100" :src="userInfo.avatar">
                {{ userInfo.first_name?.[0] || userInfo.username?.[0]?.toUpperCase() }}
              </el-avatar>
              <div class="avatar-actions">
                <el-button size="small" @click="showAvatarDialog = true">
                  更换头像
                </el-button>
              </div>
            </div>
            <div class="basic-info">
              <h3>{{ userInfo.first_name }} {{ userInfo.last_name }}</h3>
              <p class="username">@{{ userInfo.username }}</p>
              <el-tag :type="getRoleType(userInfo.role)">
                {{ getRoleLabel(userInfo.role) }}
              </el-tag>
            </div>
          </div>

          <el-divider />

          <div class="info-list">
            <div class="info-item">
              <span class="label">邮箱</span>
              <span class="value">{{ userInfo.email }}</span>
            </div>
            <div class="info-item">
              <span class="label">手机号</span>
              <span class="value">{{ userInfo.phone || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">部门</span>
              <span class="value">{{ userInfo.department || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">状态</span>
              <el-tag :type="userInfo.is_active ? 'success' : 'danger'" size="small">
                {{ userInfo.is_active ? '正常' : '禁用' }}
              </el-tag>
            </div>
            <div class="info-item">
              <span class="label">最后登录</span>
              <span class="value">{{ formatDateTime(userInfo.last_login) }}</span>
            </div>
            <div class="info-item">
              <span class="label">注册时间</span>
              <span class="value">{{ formatDateTime(userInfo.created_at) }}</span>
            </div>
          </div>
        </el-card>

        <!-- 快速操作 -->
        <el-card class="quick-actions">
          <template #header>
            <h4>快速操作</h4>
          </template>
          <div class="action-list">
            <el-button type="primary" plain @click="showPasswordDialog = true" block>
              <el-icon><Lock /></el-icon>
              修改密码
            </el-button>
            <el-button @click="showEditDialog = true" block>
              <el-icon><Edit /></el-icon>
              编辑资料
            </el-button>
            <el-button type="warning" plain @click="exportPersonalData" block>
              <el-icon><Download /></el-icon>
              导出个人数据
            </el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧详细信息 -->
      <el-col :span="16">
        <el-card class="detail-card">
          <el-tabs v-model="activeTab" type="border-card">
            <!-- 个人信息编辑 -->
            <el-tab-pane label="个人信息" name="profile">
              <div class="profile-content">
                <el-form
                  ref="profileFormRef"
                  :model="profileForm"
                  :rules="profileRules"
                  label-width="100px"
                >
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="姓名" prop="first_name">
                        <el-input v-model="profileForm.first_name" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="姓氏" prop="last_name">
                        <el-input v-model="profileForm.last_name" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="邮箱" prop="email">
                        <el-input v-model="profileForm.email" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="手机号">
                        <el-input v-model="profileForm.phone" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="部门">
                        <el-select v-model="profileForm.department" style="width: 100%">
                          <el-option
                            v-for="dept in departments"
                            :key="dept.id"
                            :label="dept.name"
                            :value="dept.name"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="班级" v-if="userInfo.role === 'student'">
                        <el-select v-model="profileForm.class_id" style="width: 100%">
                          <el-option
                            v-for="cls in classes"
                            :key="cls.id"
                            :label="cls.name"
                            :value="cls.id"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item label="个人简介">
                    <el-input
                      v-model="profileForm.bio"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入个人简介"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="updateProfile" :loading="updating">
                      保存修改
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>

            <!-- 学习统计 (学生角色) -->
            <el-tab-pane v-if="userInfo.role === 'student'" label="学习统计" name="stats">
              <div class="stats-content">
                <el-row :gutter="20">
                  <el-col :span="6">
                    <div class="stat-card">
                      <div class="stat-number">{{ studentStats.totalExams }}</div>
                      <div class="stat-label">参加考试</div>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="stat-card">
                      <div class="stat-number">{{ studentStats.averageScore }}</div>
                      <div class="stat-label">平均分</div>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="stat-card">
                      <div class="stat-number">{{ studentStats.passRate }}%</div>
                      <div class="stat-label">及格率</div>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="stat-card">
                      <div class="stat-number">{{ studentStats.rank }}</div>
                      <div class="stat-label">班级排名</div>
                    </div>
                  </el-col>
                </el-row>

                <div class="chart-section">
                  <h4>成绩趋势</h4>
                  <div ref="scoreChart" class="chart-container"></div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 活动日志 -->
            <el-tab-pane label="活动日志" name="activity">
              <div class="activity-content">
                <el-table :data="activityLogs" v-loading="loadingLogs">
                  <el-table-column label="时间" width="180">
                    <template #default="{ row }">
                      {{ formatDateTime(row.timestamp) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" prop="action" width="120" />
                  <el-table-column label="描述" prop="description" />
                  <el-table-column label="IP地址" prop="ip_address" width="120" />
                </el-table>

                <div class="pagination-wrapper">
                  <el-pagination
                    v-model:current-page="logPagination.current"
                    :page-size="logPagination.pageSize"
                    :total="logPagination.total"
                    layout="prev, pager, next"
                    @current-change="fetchActivityLogs"
                  />
                </div>
              </div>
            </el-tab-pane>

            <!-- 通知设置 -->
            <el-tab-pane label="通知设置" name="notifications">
              <div class="notification-content">
                <el-form :model="notificationSettings" label-width="150px">
                  <h4>考试通知</h4>
                  <el-form-item label="考试提醒">
                    <el-switch v-model="notificationSettings.exam_reminder" />
                  </el-form-item>
                  <el-form-item label="成绩发布通知">
                    <el-switch v-model="notificationSettings.grade_published" />
                  </el-form-item>
                  <el-form-item label="考试开始提醒">
                    <el-switch v-model="notificationSettings.exam_start" />
                  </el-form-item>

                  <h4>系统通知</h4>
                  <el-form-item label="系统维护通知">
                    <el-switch v-model="notificationSettings.system_maintenance" />
                  </el-form-item>
                  <el-form-item label="功能更新通知">
                    <el-switch v-model="notificationSettings.feature_updates" />
                  </el-form-item>

                  <h4>邮件通知</h4>
                  <el-form-item label="接收邮件通知">
                    <el-switch v-model="notificationSettings.email_enabled" />
                  </el-form-item>
                  <el-form-item label="邮件频率">
                    <el-radio-group v-model="notificationSettings.email_frequency">
                      <el-radio value="realtime">实时</el-radio>
                      <el-radio value="daily">每日汇总</el-radio>
                      <el-radio value="weekly">每周汇总</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" @click="saveNotificationSettings" :loading="savingNotifications">
                      保存设置
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑资料对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑个人资料" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="姓名">
          <el-input v-model="editForm.first_name" />
        </el-form-item>
        <el-form-item label="姓氏">
          <el-input v-model="editForm.last_name" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="quickUpdateProfile" :loading="updating">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="450px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="当前密码" prop="old_password">
          <el-input
            v-model="passwordForm.old_password"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
          <el-input
            v-model="passwordForm.new_password"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirm_password">
          <el-input
            v-model="passwordForm.confirm_password"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="changePassword" :loading="changingPassword">
          修改密码
        </el-button>
      </template>
    </el-dialog>

    <!-- 更换头像对话框 -->
    <el-dialog v-model="showAvatarDialog" title="更换头像" width="400px">
      <div class="avatar-upload">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          action="/api/v1/users/me/update-avatar/"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar-preview" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tips">
          <p>支持 JPG、PNG 格式，文件大小不超过 2MB</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="showAvatarDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAvatarChange">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Lock,
  Edit,
  Download,
  Plus
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { userApi, authApi } from '@/api'
import type { User } from '@/types'

// 响应式数据
const userInfo = ref<User>({} as User)
const loading = ref(false)
const updating = ref(false)
const changingPassword = ref(false)
const savingNotifications = ref(false)
const loadingLogs = ref(false)
const activeTab = ref('profile')

// 基础数据
const departments = ref<any[]>([])
const classes = ref<any[]>([])

// 对话框状态
const showEditDialog = ref(false)
const showPasswordDialog = ref(false)
const showAvatarDialog = ref(false)

// 表单数据
const profileFormRef = ref()
const profileForm = reactive({
  first_name: '',
  last_name: '',
  email: '',
  phone: '',
  department: '',
  class_id: null as number | null,
  bio: ''
})

const profileRules = {
  first_name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const editForm = reactive({
  first_name: '',
  last_name: '',
  email: '',
  phone: ''
})

const passwordFormRef = ref()
const passwordForm = reactive({
  old_password: '',
  new_password: '',
  confirm_password: ''
})

const passwordRules = {
  old_password: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6个字符', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.new_password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 头像相关
const imageUrl = ref('')
const newAvatarFile = ref<File | null>(null)

// 通知设置
const notificationSettings = reactive({
  exam_reminder: true,
  grade_published: true,
  exam_start: true,
  system_maintenance: true,
  feature_updates: false,
  email_enabled: true,
  email_frequency: 'realtime'
})

// 学生统计
const studentStats = reactive({
  totalExams: 0,
  averageScore: 0,
  passRate: 0,
  rank: 0
})

// 活动日志
const activityLogs = ref<any[]>([])
const logPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 图表实例
const scoreChart = ref<HTMLElement>()
let scoreChartInstance: echarts.ECharts | null = null

// 获取当前用户信息
const fetchUserInfo = async () => {
  try {
    const response = await userApi.getCurrentUser()
    if (response.data) {
      userInfo.value = response.data
      imageUrl.value = response.data.avatar || ''

      // 填充表单数据
      Object.assign(profileForm, {
        first_name: response.data.first_name,
        last_name: response.data.last_name,
        email: response.data.email,
        phone: response.data.phone,
        department: response.data.department,
        class_id: response.data.class_id,
        bio: response.data.bio || ''
      })

      Object.assign(editForm, {
        first_name: response.data.first_name,
        last_name: response.data.last_name,
        email: response.data.email,
        phone: response.data.phone
      })
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 获取基础数据
const fetchBaseData = async () => {
  try {
    const [deptResponse, classResponse] = await Promise.all([
      userApi.getDepartments(),
      userApi.getClasses({ page_size: 1000 })
    ])

    if (deptResponse.data) {
      departments.value = deptResponse.data
    }

    if (classResponse.data?.results) {
      classes.value = classResponse.data.results
    }
  } catch (error) {
    console.error('获取基础数据失败:', error)
  }
}

// 获取学生统计
const fetchStudentStats = async () => {
  if (userInfo.value.role !== 'student') return

  try {
    // TODO: 实现学生统计API
    // const response = await userApi.getStudentStats()
    // if (response.data) {
    //   Object.assign(studentStats, response.data)
    // }

    // 模拟数据
    Object.assign(studentStats, {
      totalExams: 15,
      averageScore: 85,
      passRate: 93,
      rank: 3
    })

    await nextTick()
    initScoreChart()
  } catch (error) {
    console.error('获取学生统计失败:', error)
  }
}

// 获取活动日志
const fetchActivityLogs = async () => {
  loadingLogs.value = true
  try {
    const response = await userApi.getUserActivityLogs({
      page: logPagination.current,
      page_size: logPagination.pageSize
    })

    if (response.data) {
      activityLogs.value = response.data.results
      logPagination.total = response.data.count
    }
  } catch (error) {
    console.error('获取活动日志失败:', error)
    ElMessage.error('获取活动日志失败')
  } finally {
    loadingLogs.value = false
  }
}

// 初始化成绩趋势图表
const initScoreChart = () => {
  if (!scoreChart.value) return

  if (scoreChartInstance) {
    scoreChartInstance.dispose()
  }

  scoreChartInstance = echarts.init(scoreChart.value)

  const option = {
    title: {
      text: '成绩趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['第1次', '第2次', '第3次', '第4次', '第5次', '第6次']
    },
    yAxis: {
      type: 'value',
      name: '分数',
      min: 0,
      max: 100
    },
    series: [{
      name: '考试成绩',
      type: 'line',
      smooth: true,
      data: [78, 82, 85, 88, 85, 90],
      itemStyle: {
        color: '#409eff'
      },
      areaStyle: {
        opacity: 0.3
      }
    }]
  }

  scoreChartInstance.setOption(option)
}

// 更新个人资料
const updateProfile = async () => {
  try {
    await profileFormRef.value.validate()

    updating.value = true
    await userApi.updateCurrentUser(profileForm)

    ElMessage.success('个人资料更新成功')
    await fetchUserInfo()
  } catch (error) {
    console.error('更新个人资料失败:', error)
    ElMessage.error('更新个人资料失败')
  } finally {
    updating.value = false
  }
}

// 快速更新资料
const quickUpdateProfile = async () => {
  try {
    updating.value = true
    await userApi.updateCurrentUser(editForm)

    ElMessage.success('个人资料更新成功')
    showEditDialog.value = false
    await fetchUserInfo()
  } catch (error) {
    console.error('更新个人资料失败:', error)
    ElMessage.error('更新个人资料失败')
  } finally {
    updating.value = false
  }
}

// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()

    changingPassword.value = true
    await userApi.changePassword(passwordForm)

    ElMessage.success('密码修改成功')
    showPasswordDialog.value = false

    // 清空表单
    Object.assign(passwordForm, {
      old_password: '',
      new_password: '',
      confirm_password: ''
    })
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败')
  } finally {
    changingPassword.value = false
  }
}

// 头像上传相关
const beforeAvatarUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }

  newAvatarFile.value = file
  imageUrl.value = URL.createObjectURL(file)
  return false // 阻止自动上传
}

const handleAvatarSuccess = (response: any) => {
  imageUrl.value = response.url
  userInfo.value.avatar = response.url
}

const confirmAvatarChange = async () => {
  if (!newAvatarFile.value) {
    ElMessage.warning('请选择头像文件')
    return
  }

  try {
    await userApi.updateAvatar(newAvatarFile.value)
    ElMessage.success('头像更新成功')
    showAvatarDialog.value = false
    await fetchUserInfo()
  } catch (error) {
    console.error('更新头像失败:', error)
    ElMessage.error('更新头像失败')
  }
}

// 保存通知设置
const saveNotificationSettings = async () => {
  try {
    savingNotifications.value = true
    // TODO: 实现通知设置保存API
    // await userApi.updateNotificationSettings(notificationSettings)

    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
    ElMessage.success('通知设置保存成功')
  } catch (error) {
    console.error('保存通知设置失败:', error)
    ElMessage.error('保存通知设置失败')
  } finally {
    savingNotifications.value = false
  }
}

// 导出个人数据
const exportPersonalData = async () => {
  try {
    // TODO: 实现个人数据导出
    ElMessage.info('个人数据导出功能开发中')
  } catch (error) {
    console.error('导出个人数据失败:', error)
    ElMessage.error('导出个人数据失败')
  }
}

// 工具函数
const getRoleType = (role: string) => {
  switch (role) {
    case 'admin': return 'danger'
    case 'teacher': return 'warning'
    case 'student': return 'success'
    default: return 'info'
  }
}

const getRoleLabel = (role: string) => {
  switch (role) {
    case 'admin': return '管理员'
    case 'teacher': return '教师'
    case 'student': return '学生'
    default: return role
  }
}

const formatDateTime = (dateTime: string | null) => {
  if (!dateTime) return '从未'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    fetchUserInfo(),
    fetchBaseData()
  ])

  if (userInfo.value.role === 'student') {
    await fetchStudentStats()
  }

  await fetchActivityLogs()
})
</script>

<style scoped lang="scss">
.profile {
  padding: 20px;
}

.profile-header {
  margin-bottom: 20px;

  h2 {
    margin: 0;
    color: #303133;
  }
}

.profile-card {
  margin-bottom: 20px;

  .avatar-section {
    text-align: center;

    .avatar-wrapper {
      position: relative;
      display: inline-block;

      .avatar-actions {
        margin-top: 12px;
      }
    }

    .basic-info {
      margin-top: 16px;

      h3 {
        margin: 0 0 8px 0;
        color: #303133;
      }

      .username {
        color: #909399;
        margin: 0 0 12px 0;
      }
    }
  }

  .info-list {
    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;

      .label {
        color: #606266;
        font-weight: 500;
      }

      .value {
        color: #303133;
      }
    }
  }
}

.quick-actions {
  .action-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
}

.detail-card {
  .profile-content {
    padding: 20px;
  }

  .stats-content {
    padding: 20px;

    .stat-card {
      text-align: center;
      padding: 20px;
      background: #f8f9fa;
      border-radius: 8px;

      .stat-number {
        font-size: 32px;
        font-weight: bold;
        color: #409eff;
        margin-bottom: 8px;
      }

      .stat-label {
        color: #606266;
        font-size: 14px;
      }
    }

    .chart-section {
      margin-top: 30px;

      h4 {
        margin-bottom: 16px;
        color: #303133;
      }

      .chart-container {
        height: 300px;
      }
    }
  }

  .activity-content {
    padding: 20px;

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }

  .notification-content {
    padding: 20px;

    h4 {
      margin: 20px 0 16px 0;
      color: #303133;
      border-bottom: 1px solid #ebeef5;
      padding-bottom: 8px;

      &:first-child {
        margin-top: 0;
      }
    }
  }
}

.avatar-upload {
  text-align: center;

  .avatar-uploader {
    .avatar-preview {
      width: 150px;
      height: 150px;
      border-radius: 50%;
      object-fit: cover;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 150px;
      height: 150px;
      line-height: 150px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 50%;
      cursor: pointer;
      transition: border-color 0.3s;

      &:hover {
        border-color: #409eff;
      }
    }
  }

  .upload-tips {
    margin-top: 12px;

    p {
      margin: 0;
      color: #909399;
      font-size: 12px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .profile {
    padding: 12px;
  }

  .el-row {
    .el-col:first-child {
      margin-bottom: 20px;
    }
  }

  .stats-content {
    .el-row {
      .el-col {
        margin-bottom: 16px;
      }
    }
  }
}
</style>